<script>
import { mapState, mapGetters } from "vuex";
const updateManager = uni.getUpdateManager();

export default {
  computed: {
    ...mapState(["userInfo", "isHome"]),
    ...mapGetters(["cartNum"]),
  },
  onLaunch() {
    if (this.$inH5 && window.matchMedia) {
      const matMedia = window.matchMedia("(prefers-color-scheme: dark)");
      this.setTheme(matMedia.matches);
      matMedia.addEventListener("change", () => {
        this.setTheme(matMedia.matches);
      });
    }
    this.setBadge();
  },
  onShow() {
    this.checkMp();
  },
  onHide() {},
  onThemeChange({ theme }) {
    this.setTheme(theme == "dark");
  },
  watch: {
    isHome(val) {
      if (val) this.setBadge();
    },
    cartNum() {
      this.setBadge();
    },
  },
  methods: {
    setBadge() {
      if (!this.isHome) return;
      const index = 2;
      if (!this.cartNum) {
        uni.removeTabBarBadge({ index });
        return;
      }
      uni.setTabBarBadge({
        index,
        text: this.cartNum + "",
      });
    },
    checkMp() {
      updateManager.onCheckForUpdate(function (res) {
        console.log("onCheckForUpdate", res.hasUpdate);
      });
      updateManager.onUpdateReady(function () {
        updateManager.applyUpdate();
      });
    },
    setTheme(isDark) {
      this.$setState({
        isDark,
      });
    },
  },
};
</script>
